<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CPU时空分析系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/luxon@3.0.1"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-luxon@1.2.0"></script>
    <style>
        :root {
            --primary: #4361ee;
            --warning: #f8961e;
            --danger: #ef233c;
            --success: #2ec4b6;
            --dark: #2b2d42;
        }

        body {
            background-color: #f8f9fa;
            font-family: 'Segoe UI', system-ui, sans-serif;
        }

        .dashboard-header {
            background: linear-gradient(135deg, var(--dark) 0%, var(--primary) 100%);
            color: white;
            padding: 1.5rem 0;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }

        .analysis-card {
            border-radius: 10px;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px rgba(0,0,0,0.05);
            background: white;
        }

        .chart-container {
            position: relative;
            height: 400px;
            margin-bottom: 1rem;
        }

        .host-selector {
            max-width: 300px;
        }

        .time-slider {
            width: 100%;
        }

        .heatmap-cell {
            cursor: pointer;
            transition: all 0.2s;
        }

        .heatmap-cell:hover {
            transform: scale(1.05);
            box-shadow: 0 0 8px rgba(0,0,0,0.2);
        }

        .badge-cpu {
            font-size: 0.75rem;
            font-weight: 500;
        }
    </style>
</head>
<body>
    <div class="dashboard-header">
        <div class="container">
            <h1><i class="bi bi-cpu"></i> CPU时空分析系统</h1>
            <p class="mb-0">主机名与时间维度联合分析</p>
        </div>
    </div>

    <div class="container">
        {% if data and data.data %}
        <!-- 控制面板 -->
        <div class="row mb-4">
            <div class="col-md-4">
                <select class="form-select host-selector" id="hostSelector">
                    <option value="">所有主机</option>
                    {% set hosts = [] %}
                    {% for item in data.data %}
                        {% if item.hostname not in hosts %}
                            {% set _ = hosts.append(item.hostname) %}
                            <option value="{{ item.hostname }}">{{ item.hostname }}</option>
                        {% endif %}
                    {% endfor %}
                </select>
            </div>
            <div class="col-md-6">
                <div class="d-flex align-items-center">
                    <span class="me-2 text-muted">时间范围:</span>
                    <input type="range" class="form-range time-slider" id="timeRange" min="0" max="100" value="100">
                    <span class="ms-2" id="timeRangeValue">全部</span>
                </div>
            </div>
            <div class="col-md-2 text-end">
                <button class="btn btn-outline-primary" id="refreshBtn">
                    <i class="bi bi-arrow-clockwise"></i> 刷新
                </button>
            </div>
        </div>

        <!-- 时空热力图 -->
        <div class="analysis-card">
            <div class="card-header">
                <h5 class="card-title mb-0"><i class="bi bi-grid-3x3"></i> CPU使用率时空热力图</h5>
            </div>
            <div class="card-body">
                <div class="chart-container">
                    <canvas id="heatmapChart"></canvas>
                </div>
            </div>
        </div>

        <!-- 主机时间趋势图 -->
        <div class="analysis-card">
            <div class="card-header">
                <div class="d-flex justify-content-between align-items-center">
                    <h5 class="card-title mb-0"><i class="bi bi-graph-up"></i> 主机CPU时间趋势</h5>
                    <div id="hostLegend" class="d-flex flex-wrap"></div>
                </div>
            </div>
            <div class="card-body">
                <div class="chart-container">
                    <canvas id="trendChart"></canvas>
                </div>
            </div>
        </div>

        <!-- 详细数据表格 -->
        <div class="analysis-card">
            <div class="card-header">
                <h5 class="card-title mb-0"><i class="bi bi-table"></i> 详细数据</h5>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead>
                            <tr>
                                <th>时间</th>
                                <th>主机名</th>
                                <th>核心</th>
                                <th>使用率</th>
                                <th>状态</th>
                            </tr>
                        </thead>
                        <tbody id="dataTable">
                            {% for item in data.data %}
                            {% set used = item.cpu_used.split('%')[0] | float %}
                            <tr data-host="{{ item.hostname }}" data-time="{{ item.date }}">
                                <td>{{ item.date }}</td>
                                <td>{{ item.hostname }}</td>
                                <td>{{ item.cpu_core }}</td>
                                <td>
                                    <div class="progress" style="height: 20px;">
                                        <div class="progress-bar bg-{{ 'danger' if used > 80 else 'warning' if used > 60 else 'success' }}"
                                             style="width: {{ used }}%">
                                            {{ item.cpu_used }}
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <span class="badge bg-{{ 'danger' if used > 80 else 'warning' if used > 60 else 'success' }} badge-cpu">
                                        {% if used > 80 %}过载{% elif used > 60 %}高负载{% else %}正常{% endif %}
                                    </span>
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        {% else %}
        <div class="alert alert-danger">
            <i class="bi bi-exclamation-triangle"></i> 错误：没有可用的CPU数据
        </div>
        {% endif %}
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 原始数据
        const rawData = {{ data.data | tojson }};

        // 处理后的数据
        let processedData = {
            hosts: [],
            timestamps: [],
            hostTimeMatrix: {}
        };

        // 图表实例
        let heatmapChart, trendChart;

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            processData();
            initHeatmap();
            initTrendChart();
            initControls();
        });

        // 数据处理函数
        function processData() {
            // 获取唯一主机名和时间戳
            processedData.hosts = [...new Set(rawData.map(item => item.hostname))];
            processedData.timestamps = [...new Set(rawData.map(item => item.date))];

            // 按时间排序
            processedData.timestamps.sort((a, b) => new Date(a) - new Date(b));

            // 构建主机-时间矩阵
            processedData.hosts.forEach(host => {
                processedData.hostTimeMatrix[host] = {};
                processedData.timestamps.forEach(time => {
                    // 计算该主机在该时间点的平均使用率
                    const items = rawData.filter(
                        item => item.hostname === host && item.date === time
                    );

                    if (items.length > 0) {
                        const avgUsed = items.reduce(
                            (sum, item) => sum + parseFloat(item.cpu_used.replace('%', '')),
                            0
                        ) / items.length;

                        processedData.hostTimeMatrix[host][time] = avgUsed.toFixed(1);
                    }
                });
            });
        }

        // 初始化热力图
        function initHeatmap() {
            const ctx = document.getElementById('heatmapChart').getContext('2d');

            // 准备热力图数据
            const data = {
                labels: processedData.timestamps.map(time =>
                    new Date(time).toLocaleTimeString()
                ),
                datasets: processedData.hosts.map((host, i) => ({
                    label: host,
                    data: processedData.timestamps.map(time => ({
                        x: new Date(time).toLocaleTimeString(),
                        y: processedData.hostTimeMatrix[host][time] || 0,
                        time: time,
                        host: host
                    })),
                    backgroundColor: `hsl(${i * 360 / processedData.hosts.length}, 70%, 50%)`
                }))
            };

            heatmapChart = new Chart(ctx, {
                type: 'bar',
                data: data,
                options: {
                    responsive: true,
                    scales: {
                        x: {
                            stacked: true,
                            title: {
                                display: true,
                                text: '时间'
                            }
                        },
                        y: {
                            stacked: true,
                            title: {
                                display: true,
                                text: 'CPU使用率 (%)'
                            },
                            min: 0,
                            max: 100
                        }
                    },
                    plugins: {
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    return `${context.dataset.label}: ${context.raw.y}%`;
                                },
                                afterLabel: function(context) {
                                    return `时间: ${context.raw.time}\n主机: ${context.raw.host}`;
                                }
                            }
                        }
                    },
                    onClick: function(evt, elements) {
                        if (elements.length > 0) {
                            const index = elements[0].index;
                            const datasetIndex = elements[0].datasetIndex;
                            const time = processedData.timestamps[index];
                            const host = processedData.hosts[datasetIndex];
                            filterData(host, time);
                        }
                    }
                }
            });
        }

        // 初始化趋势图
        function initTrendChart() {
            const ctx = document.getElementById('trendChart').getContext('2d');
            const legendContainer = document.getElementById('hostLegend');

            // 生成图例
            legendContainer.innerHTML = processedData.hosts.map((host, i) => `
                <div class="form-check form-check-inline ms-2">
                    <input class="form-check-input host-check"
                           type="checkbox"
                           id="check-${host}"
                           value="${host}"
                           checked
                           style="background-color: hsl(${i * 360 / processedData.hosts.length}, 70%, 50%)">
                    <label class="form-check-label small" for="check-${host}">${host}</label>
                </div>
            `).join('');

            // 准备趋势图数据
            const datasets = processedData.hosts.map((host, i) => ({
                label: host,
                data: processedData.timestamps.map(time => ({
                    x: time,
                    y: processedData.hostTimeMatrix[host][time] || 0
                })),
                borderColor: `hsl(${i * 360 / processedData.hosts.length}, 70%, 50%)`,
                backgroundColor: `hsla(${i * 360 / processedData.hosts.length}, 70%, 50%, 0.1)`,
                tension: 0.3,
                fill: true,
                borderWidth: 2
            }));

            trendChart = new Chart(ctx, {
                type: 'line',
                data: {
                    datasets: datasets
                },
                options: {
                    responsive: true,
                    interaction: {
                        intersect: false,
                        mode: 'index'
                    },
                    scales: {
                        x: {
                            type: 'time',
                            time: {
                                parser: 'yyyy-MM-dd HH:mm:ss',
                                tooltipFormat: 'MM-dd HH:mm'
                            },
                            title: {
                                display: true,
                                text: '时间'
                            }
                        },
                        y: {
                            title: {
                                display: true,
                                text: 'CPU使用率 (%)'
                            },
                            min: 0,
                            max: 100
                        }
                    },
                    plugins: {
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    return `${context.dataset.label}: ${context.parsed.y}%`;
                                }
                            }
                        }
                    }
                }
            });

            // 图例点击事件
            document.querySelectorAll('.host-check').forEach(checkbox => {
                checkbox.addEventListener('change', function() {
                    const host = this.value;
                    const meta = trendChart.getDatasetMeta(
                        processedData.hosts.indexOf(host)
                    );
                    meta.hidden = !this.checked;
                    trendChart.update();
                });
            });
        }

        // 初始化控制组件
        function initControls() {
            // 主机选择器
            document.getElementById('hostSelector').addEventListener('change', function() {
                const host = this.value;
                filterData(host);
            });

            // 时间范围滑块
            document.getElementById('timeRange').addEventListener('input', function() {
                const percent = this.value;
                const timeCount = processedData.timestamps.length;
                const showCount = Math.ceil(timeCount * percent / 100);
                const startIndex = timeCount - showCount;

                document.getElementById('timeRangeValue').textContent =
                    percent === '100' ? '全部' : `最近 ${showCount} 个时间点`;

                // 更新时间范围
                if (trendChart) {
                    trendChart.options.scales.x.min = startIndex >= 0 ?
                        processedData.timestamps[startIndex] : undefined;
                    trendChart.update();
                }
            });

            // 刷新按钮
            document.getElementById('refreshBtn').addEventListener('click', function() {
                window.location.reload();
            });
        }

        // 数据筛选函数
        function filterData(host, time) {
            const rows = document.querySelectorAll('#dataTable tr');

            rows.forEach(row => {
                const show =
                    (!host || row.dataset.host === host) &&
                    (!time || row.dataset.time === time);
                row.style.display = show ? '' : 'none';
            });

            // 高亮相关图表元素
            if (heatmapChart) {
                heatmapChart.data.datasets.forEach((dataset, i) => {
                    dataset.backgroundColor = `hsl(${i * 360 / processedData.hosts.length}, ${host && dataset.label !== host ? '30' : '70'}%, 50%)`;
                });
                heatmapChart.update();
            }
        }
    </script>
</body>
</html>